<?php
/*
 * code to add a new user account to the system using data posted from newuser.php
*/
session_start();
if(!isset($_SESSION['userid'])){
	header('location:../login.php');
}
else
{

	// Create connection
	include("../inc_files/utils/dbconnection.php");

	/*check to see if a user already exists with this username
	 *if so add an incremental number to the end e.g.
	*if u.name exists create u.name1, u.name2 etc.
	*/
	$userID = $mysqli->real_escape_string($_POST['userid']);

	$resultCount = 0;
	$noOfClashes = 0;
	$UserIDSuffix = "";
	do{
		//query for existing userIDs that clash with the suggested one
		if($noOfClashes > 0)  $UserIDSuffix=$noOfClashes;
		$query ="SELECT * FROM staff WHERE UserID='".$userID.$UserIDSuffix."';";
		$result = $mysqli->query( $query );

		//count the number of returned results
		$resultCount = $result->num_rows;
		$noOfClashes++;

	} while ($resultCount != 0);

	$userID = $userID.$UserIDSuffix;

	// add the function to creat a salt for encryption
	include("../inc_files/utils/salt.php");

	//sanitise the input data
	$firstName = $mysqli->real_escape_string($_POST['firstname']);
	$lastName = $mysqli->real_escape_string($_POST['lastname']);
	$userRole = $mysqli->real_escape_string($_POST['userrole']);

	//create a hashed password
	$hashPassword = crypt(trim($_POST['password']),createSalt());

	if(strlen($firstName) > 0 && strlen($lastName) > 0 && strlen($userID) > 1){
		// insert the customer details into the database

		$query="INSERT INTO staff (FirstName, LastName, Role, UserID, Password)
		VALUES
		('$firstName','$lastName','$userRole','$userID','$hashPassword')";

		$mysqli->query($query) or die($mysqli->error);

		//tidy up database connection
		$mysqli->close();
		//redirect to users list
		header("Location:listusers.php");
	} else {
		echo "Error adding new user";
	}
}
?>


